<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>滚动文字canvas</title>
		<style type="text/css">
			html,
			body,
			canvas {
				overflow: hidden;
				height: 100%;
				width: 100%;
				margin: 0;
				padding: 0;
				background-color: black;
			}
		</style>
	</head>
	<body>
		<canvas id="black-canvas"></canvas>
		<script type="text/javascript">
			window.onload = function() {
				var blackCavas = document.getElementById('black-canvas');
				blackCavas.height = blackCavas.offsetHeight;
				blackCavas.width = blackCavas.offsetWidth;
				var ctx = blackCavas.getContext('2d');
				// 填充渐变
				var grd=ctx.createLinearGradient(0, 0, 0, blackCavas.height);
				grd.addColorStop(0,"black");
				grd.addColorStop(0.5,"#007000");
				grd.addColorStop(1,"black");
				ctx.fillStyle=grd;
				ctx.font = "18px Arial";
				var textNum = 0;
				var fontArrs = [];
				
				// 创建对象
				function create(x) {
					var fontArr = [];
					var num = 30 + Math.floor(Math.random() * 30);
					var y = -Math.floor(blackCavas.height * Math.random());
					for (var i = 0; i <= num; i++) {
						fontArr.push({
							text: textNum++,
							x: x,
							y: y + 20 * i
						});
						textNum %= 2;
					}
					return fontArr;
				}

				// 画图主方法
				function draw(fontArr, x, y) {
					var len = fontArr.length;
					ctx.clearRect(x, 0, 20, blackCavas.height);
					for (var j = 0; j < len; j++) {
						var obj = fontArr[j];
						obj.y = obj.y + y;
						ctx.fillText(obj.text, obj.x, obj.y);
					}
					// 如果画到结束了，则重新画
					if (fontArr[len - 1].y >= len * 20 + blackCavas.height) {
						setTimeout(draw, Math.floor(Math.random() * 1000), create(x), x, 0);
					} else {
						setTimeout(draw, 50, fontArr, x, y+10);
					}
				}

				// 开始画图
				var rnum = 30;
				var singleWidth = (blackCavas.width - 40) / rnum;
				for (var i = 0; i <= rnum; i++) {
					var x =  10 + i * singleWidth ;
					setTimeout(function(x) {
						draw(create(x), x, 0);
					}, Math.floor(Math.random() * 1000), x)
				}
			}
		</script>
	</body>
</html>
